'''
solargis提供了一个可以访问一年总量辐照数据的接口：
有访问次数限制: 网址如下：
https://apps.solargis.com/prospect/map?c=11.609193,8.349609,3&s=-14.771095,67.557308
'''
import os
import shutil
import pandas as pd
import requests,time
from openpyxl import load_workbook

class GrapSolargis(object):
    def __init__(self,df=None,filename=None,query=None):
        if not df is None:
            self.df = df
            self.get_batched_data(filename)
        elif not query is None:
            self.address = query[0]
            self.lon = query[1]
            self.lat = query[2]
            self.solargis_data(self.address, self.lon, self.lat)
        else:
            raise ValueError('请输入df或者query')

    def safe_save(self, wb, filename):
        temp_path = f'../file/solargis/{filename}_temp.xlsx'
        final_path = f'../file/solargis/{filename}.xlsx'
        wb.save(temp_path)  # 先写入临时文件
        if os.path.exists(final_path):
            os.remove(final_path)  # 删除旧文件
        shutil.move(temp_path, final_path)  # 原子操作
    def get_batched_data(self,filename):
        wb = load_workbook(f'../file/solargis/{filename}.xlsx') #需要先创建空文件
        ws = wb.active
        for row in self.df.iterrows():
            address,lon,lat = row[1]['address'],row[1]['lon'],row[1]['lat']
            data = self.solargis_data(address,lon,lat)
            for key,value in data.items():
                row[1][key] = value
            # 新增表头检查逻辑
            # todo: 这里表头会被写到第二行，why？
            if ws.max_row == 0 or (ws.max_row == 1 and all(cell.value is None for cell in ws[1])):
                header = list(row[1].index)
                ws.append(header)
                self.safe_save(wb, filename)
            # 上面的ws.max_row的逻辑判断语句没有效果：
            columns_order = list(row[1].index)
            # ws.append(columns_order)
            # columns_order = [cell.value for cell in ws[1]]  # 动态获取表头顺序
            data_row = [row[1].get(col, None) for col in columns_order]  # 自动对齐
            ws.append(data_row)
            self.safe_save(wb, filename)
        wb.close()

    def solargis_data(self, address,lon,lat):
        headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cookie': 'solargis-_zldp=/E67GA0hRBrl+4IeY4+gIoREahMlACWGg46fRQfTtP8iiplH+OKsWY2vLYODYmbzLfwiiIiQ7qg=;\
            _hjSessionUser_2129262=eyJpZCI6ImNkMGM2NmJhLTA0ZDgtNTg4NC05ZTBjLTBlN2RiODM0YmI2ZSIsImNyZWF0ZWQiOjE2ODQxMTg2NTEwNTUsImV4aXN0aW5nIjp0cnVlfQ==;\
            solargis-_zldt=80069bf9-5e41-4687-8f1a-742b79a70a7e-0; _ga=GA1.2.117052784.1684549007; _gid=GA1.2.1204670379.1684549007; _gat=1',
            'referer': 'https://apps.solargis.com/prospect/map?c=39.7023,116.411648,12&s=39.702183,116.411895',
            'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            "sec-fetch-site": 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42'
        }
        URL = 'https://apps.solargis.com/api/data/lta?loc=%s,%s' % (lat, lon)
        ###根据经纬度对URL进行更新
        try:
            response = requests.get(URL, headers=headers)
            if response.status_code == 200:
                data = response.json()['annual']['data']
                # print(address,lon,lat)
                print('data',data)
                print('*******************************************************')
                time.sleep(100)
                return data
        except requests.exceptions.ConnectionError:
            print(address, ' 未找到数据！')
            print('*******************************************************')
            time.sleep(300)

if __name__ == '__main__':
    df = pd.DataFrame({'address':['shanghia', 'beijing'], 'lon': [121.472644, 116.407396], 'lat': [31.231707, 39.904987]})
    GrapSolargis(df=df,filename='test')
    # GrapSolargis(query=['上海','121.472644','31.231707'])



